import tkinter as tk
from tkinter import ttk, messagebox
import re
from database import DatabaseManager
import os
import sys


class AddEmployeeWindow:
    def __init__(self, parent, icon_path="asset/OIP-C.ico"):
        self.parent = parent
        self.db = DatabaseManager()
        self.icon_path = icon_path

        # 创建新窗口
        self.top = tk.Toplevel(parent)
        self.top.title("职工信息录入")
        self.top.geometry("350x350")
        self.top.protocol("WM_DELETE_WINDOW", self.on_close)

        # 设置窗口图标（新增代码）
        self._set_window_icon()

        # 创建表单框架
        form_frame = ttk.LabelFrame(self.top, text="职工信息录入", padding=20)
        form_frame.pack(fill=tk.BOTH, expand=True)

        # 字段配置（必填字段标记）
        self.fields = [
            {"name": "employee_id", "label": "职工号:", "required": True, "type": "str"},
            {"name": "name", "label": "姓名:", "required": True, "type": "str"},
            {"name": "age", "label": "年龄:", "required": True, "type": "int"},
            {"name": "gender", "label": "性别:", "required": True, "type": "enum", "options": ["男", "女"]},
            {"name": "education", "label": "学历:", "required": True, "type": "str"},
            {"name": "salary", "label": "工资:", "required": True, "type": "int"},
            {"name": "address", "label": "住址:", "required": False, "type": "str"},
            {"name": "phone", "label": "电话:", "required": False, "type": "phone"}
        ]

        # 动态生成表单字段
        self.entries = {}
        self.create_form_fields(form_frame)

        # 创建操作按钮
        btn_frame = ttk.Frame(self.top, padding=10)
        btn_frame.pack(fill=tk.X)

        submit_btn = ttk.Button(
            btn_frame,
            text="提交",
            command=self.submit_form
        )
        submit_btn.pack(side=tk.LEFT, padx=5, pady=5)

        clear_btn = ttk.Button(
            btn_frame,
            text="重置",
            command=self.clear_form
        )
        clear_btn.pack(side=tk.LEFT, padx=5, pady=5)

    def _set_window_icon(self):
        """设置窗口图标（新增方法）"""
        if not self.icon_path:
            return

        try:
            # 尝试设置窗口图标
            if sys.platform == "win32":
                self.top.iconbitmap(self.icon_path)
            else:
                # macOS/Linux使用PhotoImage方式
                img = tk.PhotoImage(file=self.icon_path)
                self.top.call('wm', 'iconphoto', self.top._w, img)

        except Exception as e:
            messagebox.showwarning("图标加载失败",
                                   f"图标加载失败：{os.path.basename(self.icon_path)}\n"
                                   f"错误详情：{str(e)}\n"
                                   f"当前路径：{os.path.abspath(self.icon_path)}")

    def create_form_fields(self, container):
        """ 动态创建表单字段 """
        for i, field in enumerate(self.fields):
            row_frame = ttk.Frame(container)
            row_frame.grid(row=i, column=0, padx=5, pady=3, sticky=tk.W)

            # 必填字段标记
            if field["required"]:
                label = f"{field['label']}*"
            else:
                label = field['label']

            # 创建标签
            lbl = ttk.Label(row_frame, text=label)
            lbl.pack(side=tk.LEFT, padx=3)

            # 创建输入组件
            if field["type"] == "enum":
                # 下拉选择框
                combo = ttk.Combobox(
                    row_frame,
                    values=field["options"],
                    state="readonly",
                    width=20
                )
                combo.pack(side=tk.LEFT, padx=3)
                self.entries[field["name"]] = combo
            else:
                # 普通输入框
                entry = ttk.Entry(row_frame, width=25)
                entry.pack(side=tk.LEFT, padx=3)
                self.entries[field["name"]] = entry

    def validate_form(self):
        """ 表单验证逻辑 """
        errors = {}

        # 必填字段验证
        for field in self.fields:
            if field["required"] and not self.entries[field["name"]].get().strip():
                errors[field["name"]] = "必填字段不能为空"

        # 数据格式验证
        try:
            age = int(self.entries["age"].get())
            if not (18 <= age <= 65):
                errors["age"] = "年龄需在18-65岁之间"
        except:
            errors["age"] = "年龄必须为数字"

        try:
            salary = int(self.entries["salary"].get())
            if salary < 0:
                errors["salary"] = "工资不能为负数"
        except:
            errors["salary"] = "工资必须为数字"

        # 电话号码验证
        phone = self.entries["phone"].get().strip()
        if phone and not re.match(r'^1[3-9]\d{9}$', phone):  #这个正则表达式匹配的是以1开头，第二位是3-9之间的数字，后面跟着9位数字的11位手机号码。
            errors["phone"] = "手机号码格式不正确"

        return errors

    def submit_form(self):
        """ 提交表单处理 """
        # 获取表单数据
        form_data = {
            field["name"]: self.entries[field["name"]].get().strip()
            for field in self.fields
        }

        # 执行验证
        errors = self.validate_form()
        if errors:
            error_msg = "\n".join([f"{k}: {v}" for k, v in errors.items()])
            messagebox.showerror("验证失败", f"请修正以下错误:\n{error_msg}")
            return

        # 准备数据库参数
        db_data = {
            "employee_id": form_data["employee_id"],
            "name": form_data["name"],
            "age": int(form_data["age"]),
            "gender": form_data["gender"],
            "education": form_data["education"],
            "salary": int(form_data["salary"]),
            "address": form_data["address"],
            "phone": form_data["phone"]
        }

        # 执行数据库插入
        try:
            if self.db.add_employee(db_data):
                messagebox.showinfo("成功", "职工信息添加成功！")
                self.clear_form()
            else:
                messagebox.showerror("失败", "数据库操作失败，请重试")
        except Exception as e:
            if "Duplicate entry" in str(e):
                messagebox.showerror("错误", "该职工号已存在！")
            else:
                messagebox.showerror("系统错误", f"发生未知错误:\n{str(e)}")

    def clear_form(self):
        """ 清空表单 """
        for field in self.fields:
            widget = self.entries[field["name"]]
            if isinstance(widget, ttk.Combobox):
                widget.set("")
            else:
                widget.delete(0, tk.END)

    def on_close(self):
        """ 窗口关闭处理 """
        self.db.close()  # 确保关闭窗口时释放数据库连接
        self.top.destroy()

# 使用示例（在main.py中调用）
# AddEmployeeWindow(parent_window)